
import pickproject
from datetime import *
import sys, os, re

        

class logger(file):
    def write(self, s):
        """Overloaded write method to add timestamp"""
        prefix =  str(datetime.now()) + ": " + s + "\n"
        file.write(self,prefix)
        print prefix

def doProcessPlan(processPlan, proj, projectName):
    for process in processPlan:
        doProcess(process, proj, projectName)      

def doProcess(moduleName, proj, projectName):
    """ Takes in a moduleName string and project object, calls module.state passing in project. Updates states."""
    module = __import__(moduleName)
    
    proj.exitState(moduleName)
    starttime = datetime.now()
    log = logger(proj.projectDir + moduleName + ".log", 'aw')
    module.start(proj, log)
    endtime = datetime.now()
    
    #the idea is that if the module.state() command throws an exception
    #then we won't ever enter the state. 
    proj.enterState(moduleName, starttime, endtime, "success")
    proj.save()

def exit():
    print "Good bye."
    sys.exit()
    
def main():
    #check projects dir for possible project files
    try:
        dirContents = os.listdir("projects")
    except OSError:
        print "No projects dir found where this script was executed from.\nExiting."
        sys.exit()
    
    #List projects
    count = -1
    for proj in dirContents:
        count += 1
        print "%d: %s" % (count, proj)
    
    selection = raw_input("Enter project number >")
    projectName = dirContents[int(selection)]
    projectDir = os.getcwd() + "/projects/" + projectName + "/"
    
    #load project class
    print projectName, projectDir
    proj = pickproject.PickProject(projectName + ".project", projectDir)
    print "Summary of states for the", projectName, "project:"
    depsDict = proj.getDepsDict()
    #flatten deps dict into list of statenames the project can possible be in
    deps = []
    for state in depsDict.keys():
        deps.append(state)

    count = -1
    for state in deps:
        count += 1
        if proj.isInState(state):
            print "%d: [DONE] %s" %(count, state)
        else:
            print "%d:        %s" %(count, state)

    
    #prompt user for dest states
    print "Enter the number of the state that you would like to move to."
    selection = raw_input("Enter number >")    
    while not proj.validState(deps[int(selection)]):
        print "invalid state, try again:"
        selection = raw_input("Enter number >")    
        
    #destStates = selection.split(',')

    #get a list of states we must move to, in order, to get to user given destination states
    processPlan = proj.getProcessPlan(deps[int(selection)])
    
    print "The following states must be reached to get to state", deps[int(selection)], "(top first)"
    for p in processPlan:
        print p

    input = ''
    while 1:
        if len(input) > 0:
            if input[0] == 'n' or input[0] == 'N':
                exit()
            if input[0] == 'y' or input[0] == 'Y':
                doProcessPlan(processPlan, proj, projectName)
                exit()
        input = raw_input('Move project to states?(Y/n)>')
        if input == '':
            input = "y"

if __name__ == "__main__":
    main()
   
   
   
    
   
